﻿using WebApp.BLL.Base;
using WebApp.DAL;
using WebApp.Models;
using WebApp.ViewModels.Manage;
using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WebApp.Common;
using WebApp.Common.Caching;

namespace WebApp.BLL.Manage
{
    public class S_menuService : BaseService<S_menu>
    {
        #region (DAL)Repository
        
        #endregion

        #region 构造

        public S_menuService() : base(new S_menuRepository()) { }

        #endregion

        #region GetName

        public string GetName(S_menu item, string lang = "zh_cn")
        {
            if (item == null)
            {
                return "";
            }
            else if ("zh_hk".Equals(lang, StringComparison.OrdinalIgnoreCase))
            {
                return item.Menuname_eng;
            }
            else
            {
                return item.Menuname_zho;
            }
        }

        #endregion

        #region 根据菜单Id查询实体

        /// <summary>
        /// 根据菜单Id查询实体
        /// </summary>
        /// <param name="menuid"></param>
        /// <returns></returns>
        public S_menu GetByMenuid(string menuid)
        {
            return this.CurrentRepository.Entities.FirstOrDefault(p => p.Menuid == menuid);
        }
        
        #endregion

        #region Exist

        public bool Exist(int id, string menuid)
        {
            if (id == 0)
            {
                return this.CurrentRepository.Entities.FirstOrDefault(p => p.Menuid == menuid) != null;
            }
            else
            {
                return this.CurrentRepository.Entities.FirstOrDefault(p => p.Id != id && p.Menuid == menuid) != null;
            }
        }

        #endregion

        #region 根据菜单Id查询菜单名称

        /// <summary>
        /// 根据菜单Id查询菜单名称
        /// </summary>
        /// <param name="menuid"></param>
        /// <returns></returns>
        public string GetMenuname(string menuid)
        {
            S_menu item = this.CurrentRepository.Entities.FirstOrDefault(p => p.Menuid == menuid);
            if (item == null)
            {
                return string.Empty;
            }
            else
            {
                return item.Menuname_zho;
            }
        }

        #endregion

        #region 获取所有菜单数据

        public IList<UserMenuModel> GetAllMenusModels()
        {
            string pamra1 = enmMenuKind.模块.ToString("d");
            string pamra2 = enmMenuKind.菜单.ToString("d");

            var T = this.CurrentRepository.Entities
                .Where(p => p.Menukind == pamra1 || p.Menukind == pamra2)
                .Where(p => p.Status == (int)enmMenuStatus.Normal)
                .Where(p => p.Pmenuid == "" || p.Pmenuid == null)
                .OrderBy(p => p.Orderseq);

            var list = T.ToList().Select(p => new UserMenuModel
            {
                Menuid = p.Menuid,
                Menuname = p.Menuname_zho,
                Menuurl = p.Menuurl,
                Menuicon = p.Menuiconmiddle,
                ChildMenus = this.GetMenusByPmenuid(p.Menuid)
            });

            return list.ToList();
        }

        public IList<UserMenuModel> GetMenusByPmenuid(string pmenuid)
        {
            string pamra1 = enmMenuKind.模块.ToString("d");
            string pamra2 = enmMenuKind.菜单.ToString("d");

            var T = this.CurrentRepository.Entities
                .Where(p => p.Menukind == pamra1 || p.Menukind == pamra2)
                .Where(p => p.Status == (int)enmMenuStatus.Normal)
                .Where(p => p.Pmenuid == pmenuid)
                .OrderBy(p => p.Orderseq);

            var list = T.Select(p => new UserMenuModel
            {
                Menuid = p.Menuid,
                Menuname = p.Menuname_zho,
                Menuurl = p.Menuurl,
                Menuicon = p.Menuiconmiddle
            });

            return list.ToList();
        }
        
        public IList<UserMenuModel> GetByPmenuid(string pmenuid)
        {
            string pamra1 = enmMenuKind.模块.ToString("d");
            string pamra2 = enmMenuKind.菜单.ToString("d");
            string pamra3 = enmMenuKind.功能.ToString("d");
            var T = this.CurrentRepository.Entities
                .Where(p => p.Menukind == pamra1 || p.Menukind == pamra2 || p.Menukind == pamra3)
                .Where(p => p.Pmenuid == pmenuid)
                .OrderBy(p => p.Orderseq);

            var list = T.Select(p => new UserMenuModel
            {
                Menuid = p.Menuid,
                Menuname = p.Menuname_zho,
                Menuurl = p.Menuurl,
                Menuicon = p.Menuiconmiddle
            });

            return list.ToList();
        }

        #endregion

        #region 查询所有模块和菜单项

        /// <summary>
        /// 查询所有模块和菜单项
        /// </summary>
        /// <returns></returns>
        public List<S_menu> GetAllMenus()
        {
            //string pamra1 = enmMenuKind.模块.ToString("d");
            //string pamra2 = enmMenuKind.菜单.ToString("d");

            var T = this.CurrentRepository.Entities
                .Where(p => p.Status != (int)enmMenuStatus.Locked);

            return T.OrderBy(p => p.Orderseq).ToList();
        }

        /// <summary>
        /// 查询所有模块和菜单项（包括Hidden的菜单）
        /// </summary>
        /// <returns></returns>
        public List<S_menu> GetAllMenusIncludeHidden()
        {
            string pamra1 = enmMenuKind.模块.ToString("d");
            string pamra2 = enmMenuKind.菜单.ToString("d");

            var T = this.CurrentRepository.Entities
                .Where(p => p.Menukind == pamra1 || p.Menukind == pamra2);

            return T.OrderBy(p => p.Orderseq).ToList();
        }

        #endregion

        #region 查询所有模块

        //public List<S_menu> GetMokuanMenus(string custcode)
        //{           
        //    string pamra1 = enmMenuKind.模块.ToString("d");
        //    var T = this.CurrentRepository.Entities.Where(p => p.Menukind == pamra1 && p.Status == (int)enmMenuStatus.Normal);
        //    if (custcode !="0000")
        //    {
        //        T = T.Where(p=>p.Tag_1==((int)enmMenuSystemtype.Customer).ToString());
        //    }
        //    return T.OrderBy(p => p.Orderseq).ToList();
        //}

        #endregion 

        #region  根据父菜单id 查询子菜单
        
        public List<S_menu> GetPmenuid(string pmenuid)
        {
            var cachekey = "S_menu_all";
            var allmenus = new MemoryCacheManager().Get<List<S_menu>>(cachekey, () =>
            {
                return this.CurrentRepository.Entities.ToList();
            });

            var T = allmenus.Where(p => p.Pmenuid == pmenuid && p.Status != (int)enmMenuStatus.Locked);
            
            return T.OrderBy(p => p.Orderseq).ToList();
        }

        #endregion 

        #region 根据菜单Url查询实体
        /// <summary>
        /// 根据菜单Url查询实体
        /// </summary>
        /// <param name="menuid"></param>
        /// <returns></returns>
        public S_menu GetByUrl(string url)
        {
            return this.CurrentRepository.Entities.FirstOrDefault(p => p.Menuurl == url);
        }

        #endregion

        #region PageList

        public List<S_menu> PageList(int pageindex, int pagesize, string searchkey, string sort, string order, out int rowscount)
        {
            var T = this.CurrentRepository.Entities;

            //根据属性名实现动态排序
            if (string.IsNullOrEmpty(sort)) sort = "Orderseq";
            T = base.SortList(T, sort, order == "asc" ? true : false);

            //查询条件
            if (!string.IsNullOrEmpty(searchkey))
            {
                T = T.Where(p => p.Menuname_zho.Contains(searchkey) || p.Menuurl.Contains(searchkey));
            }

            //返回记录数
            rowscount = T.Count();

            //返回分页结果
            return this.CurrentRepository.PageList(T, pageindex, pagesize).ToList();
        }

        #endregion

        #region ListTree

        public void ClearCache()
        {
            var cachekey = "S_menu_all";
            new MemoryCacheManager().Remove(cachekey);
        }

        public List<MenuTreeModel> ListTree(string pmenuid)
        {
            var cachekey = "S_menu_all";
            var allmenus = new MemoryCacheManager().Get<List<S_menu>>(cachekey, () =>
            {
                return this.CurrentRepository.Entities.ToList();
            });

            var list = allmenus.Where(p => p.Pmenuid == pmenuid).OrderBy(p => p.Orderseq).Select(p => new MenuTreeModel(p)).ToList();

            foreach (var item in list)
            {
                item.children = this.ListTree(item.Menuid);

                if (item.Menukind == enmMenuKind.菜单.ToString("d") && item.children.Count > 0)
                {
                    item.state = "closed";
                }
            }

            return list;
        }

        #endregion

        #region Save

        public bool Save(S_menu item)
        {
            if (item.Id == 0)
            {
                //item.Status = 0;
                this.CurrentRepository.Add(item);
            }
            else
            {
                this.CurrentRepository.Update(item);
            }

            return true;
        }

        #endregion

        #region 删除

        public bool DeleteByIds(string ids)
        {
            foreach (string id in ids.Split(','))
            {
                if (string.IsNullOrEmpty(id)) continue;

                //物理删除
                var item = this.CurrentRepository.Find(Convert.ToInt32(id));
                this.CurrentRepository.Delete(item, false);
            }

            this.CurrentRepository.Save();

            return true;
        }

        #endregion

        #region 获取菜单图标（Html文字）
        /// <summary>
        /// 获取菜单图标（Html文字）
        /// </summary>
        /// <param name="menuid"></param>
        /// <returns></returns>
        public string GetMenuIconByAction(string menuid = "")
        {

            S_menu menu = null;
            //没有给Menuid时根据url查找
            if (string.IsNullOrEmpty(menuid))
            {
                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    string url = HttpContext.Current.Request.RawUrl;
                    menu = GetByUrl(url);
                }
                else
                {
                    return string.Empty;
                }
            }
            //按Menuid查找
            else
            {
                menu = GetByMenuid(menuid);
            }

            if (menu == null) return string.Empty;
            return menu.Menuiconmiddle;
        }
        
        #endregion

        #region 默认模板菜单权限

        public List<S_menu> GetDefaultMenu()
        {
            return this.CurrentRepository.Entities.Where(p => p.Pmenuid == "Study.Patient").ToList();
        }

        #endregion

        #region 模糊查询
        /// <summary>
        /// 模糊查询
        /// </summary>
        /// <param name="likeorderby">orderby</param>
        /// <param name="menukind">menukind</param>
        /// <returns></returns>
        public List<S_menu> GetFuzzySelect(string likeorderby, string menukind)
        {
            return this.CurrentRepository.Entities
                .Where(p => p.Menukind == menukind & p.Orderseq.Contains(likeorderby))
                .OrderBy(p => p.Orderseq)
                .ToList();
        }
        #endregion

        //#region 查询课题设置权限

        //public S_menu GetStudyEditActions()
        //{
        //    return this.CurrentRepository.Entities.FirstOrDefault(p => p.Menuid == "Study.Edit");
        //}

        //#endregion

        //#region 查询课题病例权限列表

        ///// <summary>
        ///// 查询课题病例权限选项
        ///// </summary>
        ///// <returns></returns>
        //public List<UserMenuModel> GetStudyPatientActions(int studyid)
        //{
        //    P_study study = new P_studyRepository().Find(studyid);
        //    if (study != null && study.Isquery != "1")
        //    {
        //        //课题未开启质疑功能时，不现实质疑和数据核查选项
        //        return this.CurrentRepository.Entities
        //       .Where(p => p.Status == (int)enmMenuStatus.Hidden && p.Pmenuid == "Study.Patient")
        //       .Where(p => p.Menuid != "Study.Patient.Query" && p.Menuid != "Study.Patient.DM")
        //       .OrderBy(p => p.Orderseq)
        //       .Select(p => new UserMenuModel
        //       {
        //           Menuid = p.Menuid,
        //           Menuname = p.Menuname_zho,
        //           Menuurl = p.Menuurl,
        //           Menuicon = p.Menuiconmiddle
        //       }).ToList();
        //    }
        //    else {
        //        return this.CurrentRepository.Entities
        //           .Where(p => p.Status == (int)enmMenuStatus.Hidden && p.Pmenuid == "Study.Patient")
        //           .OrderBy(p => p.Orderseq)
        //           .Select(p => new UserMenuModel
        //           {
        //               Menuid = p.Menuid,
        //               Menuname = p.Menuname_zho,
        //               Menuurl = p.Menuurl,
        //               Menuicon = p.Menuiconmiddle
        //           }).ToList();
        //    }
           
        //}

        //#endregion

        #region 随访菜单

        public List<S_menu> GetCrmMenus()
        {
            string pamra1 = enmMenuKind.菜单.ToString("d");
            return this.CurrentRepository.Entities.Where(p=>p.Pmenuid=="Crm").Where(p=>p.Menukind==pamra1).ToList();
        }
            
        #endregion 

        #region  根据父菜单Id查找所有子菜单

        public List<S_menu> GetPmenus(string pmenuid)
        {
            string pamra1 = enmMenuKind.菜单.ToString("d");
            return this.CurrentRepository.Entities.Where(p=>p.Pmenuid==pmenuid)
                .Where(p=>p.Menukind==pamra1)
                .OrderBy(p=>p.Orderseq)
                .ToList();
        }

        #endregion 
        
        #region GetNewSort

        public string GetNewSort(string pmenuid)
        {
            var pmenu = this.CurrentRepository.Entities.Where(p => p.Menuid == pmenuid)
                .FirstOrDefault();

            if (pmenu == null)
            {
                return string.Empty;
            }

            var maxmenu = this.CurrentRepository.Entities.Where(p => p.Pmenuid == pmenuid)
                .OrderByDescending(p => p.Orderseq)
                .FirstOrDefault();

            if (maxmenu == null)
            {
                return pmenu.Orderseq + ".01";
            }
            else
            {
                //var maxnum = Utils.NvInt(maxmenu.Orderseq.Replace(pmenu.Orderseq + ".", ""));
                int maxnum = 1;
                if (maxmenu.Orderseq.IndexOf(".") > 0)
                {
                    maxnum = Utils.NvInt(maxmenu.Orderseq.Substring(maxmenu.Orderseq.LastIndexOf(".") + 1));
                }

                return pmenu.Orderseq + "." + (maxnum + 1).ToString().PadLeft(2, '0');
            }
        }

        #endregion

    }
}
